package org.mirrentools.remoteattendance;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.ConcurrentLinkedDeque;

/**
 * 普通的日志文件
 * @author <a href="https://mirrentools.org">Mirren</a>
 */
public class Logger {
  /**
   * 是否打印日志
   */
  private static boolean IS_LOG;
  /**
   * 日志的队列
   */
  private static ConcurrentLinkedDeque<String> LOG_QUEUE;

  static {
    IS_LOG = MainApplication.OPTIONS.logger();
    LOG_QUEUE = new ConcurrentLinkedDeque<>();
  }

  /**
   * 打印字符串日志
   *
   * @param msg 日志信息
   */
  public static void log(String msg) {
    log(msg, null);
  }

  /**
   * 打印带异常信息的队列
   *
   * @param massage 日志信息
   * @param cause   异常信息
   */
  public static void log(String massage, Throwable cause) {
    String msg = "[" + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + "] " + massage;
    while (LOG_QUEUE != null && LOG_QUEUE.size() > 2000) {
      LOG_QUEUE.poll();
    }
    synchronized (Logger.class) {
      if (IS_LOG) {
        System.out.println(msg);
      }
      LOG_QUEUE.offer(msg);
      if (cause != null) {
        if (IS_LOG) {
          cause.printStackTrace();
        }
        StackTraceElement[] trace = cause.getStackTrace();
        if (trace.length == 0) {
          LOG_QUEUE.offer(cause.toString());
        } else {
          for (StackTraceElement element : trace) {
            LOG_QUEUE.offer(element.toString());
          }
        }

      }
    }
  }

  /**
   * @return 日志信息
   */
  public static String info() {
    StringBuilder builder = new StringBuilder();
    LOG_QUEUE.forEach(e -> {
      builder.append(e).append("\r\n");
    });
    return builder.toString();
  }

}
